import { FC, useMemo } from 'react';
import { ProCard, ProForm, ProFormDigit, ProFormList, ProFormSelect, ProList } from '@ant-design/pro-components';
import { useRequest } from 'ahooks';
import { Button, Flex, message, Modal, Popconfirm, Tag } from 'antd';
import dayjs from 'dayjs';
import { BuyRecordStatus } from '@/constants/trade';
// import { getBasics } from '@/service/apis/data-source';
import { batchBuy, getBuyList, sellStock } from '@/service/apis/trade';

const Trade: FC = () => {
  const [sellForm] = ProForm.useForm();
  const [batchBuyForm] = ProForm.useForm();
  const { run: requestBatchBuy } = useRequest(batchBuy, {
    manual: true,
    onSuccess: () => {
      message.success('批量提交买入记录成功');
    },
  });

  const { run: requestSell } = useRequest(sellStock, {
    manual: true,
    onSuccess: () => {
      message.success('卖出成功');
    },
  });

  // const { data: basicOptions }: any = useRequest(getBasics);

  const { data, loading }: any = useRequest(getBuyList);

  const dataSource = useMemo(() => {
    return data?.map(({ name, code, market, volume, status, createTime, price }: any) => ({
      title: <span className="text-base font-bold mb-4">{name}</span>,
      subTitle: (
        <div className="text-base font-bold">
          <Tag color="#5BD8A6" className="text-base font-bold">{`${market}.${code}`}</Tag>
          <span className="text-gray-600 mr-4">
            <span>买入时间:</span>
            <span>{dayjs(+createTime).format('YYYY/MM/DD HH:mm:ss')}</span>
          </span>
          <span className="text-red-600 mr-4">
            <span>买入价格:</span>
            <span>{price}</span>
          </span>
          <span className="text-blue-600 mr-4">
            <span>买入数量(股):</span>
            <span>{price}</span>
          </span>
        </div>
      ),
      actions: [
        <Button
          disabled={status === BuyRecordStatus.SELL}
          onClick={() => {
            sellForm.setFieldsValue({
              code,
              price: undefined,
              volume,
            });
            Modal.confirm({
              title: `卖出-${name}`,
              closable: true,
              content: (
                <ProForm form={sellForm} submitter={false} layout="horizontal" className="mt-4">
                  <ProForm.Item name={'code'} hidden />
                  <ProFormDigit name={'price'} label="卖出价格" rules={[{ required: true }]} />
                  <ProFormDigit name={'volume'} label="卖出股数" rules={[{ required: true }]} />
                </ProForm>
              ),
              onOk: async () => {
                return sellForm?.validateFields().then(() => {
                  return requestSell(sellForm?.getFieldsValue());
                });
              },
            });
          }}
        >
          卖出
        </Button>,
        <Popconfirm title="确定删除该买入记录吗" okText="确认" cancelText="取消">
          <Button type="primary" danger disabled={status === BuyRecordStatus.SELL}>
            删除
          </Button>
        </Popconfirm>,
      ],
      // description: <div className="my-4"></div>,
    }));
  }, [data]);
  // eslint-disable-next-line padding-line-between-statements
  return (
    <ProCard className="mx-4">
      <Button
        onClick={() => {
          batchBuyForm?.resetFields();
          Modal.confirm({
            title: `批量买入`,
            closable: true,
            width: 888,
            content: (
              <ProForm form={batchBuyForm} submitter={false} layout="horizontal" className="mt-4">
                <ProFormList
                  name="records"
                  alwaysShowItemLabel
                  copyIconProps={false}
                  initialValue={[
                    {
                      useMode: 'chapter',
                    },
                  ]}
                  creatorButtonProps={{
                    position: 'bottom',
                    creatorButtonText: '新增',
                  }}
                  creatorRecord={{
                    useMode: 'none',
                  }}
                >
                  <Flex>
                    <ProFormSelect
                      name={'code'}
                      label="股票代码"
                      rules={[{ required: true }]}
                      fieldProps={{
                        showSearch: true,
                        // options: basicOptions?.map(({ code, name }: any) => ({
                        //   label: `${name} ${code}`,
                        //   value: code,
                        // })),
                      }}
                      width={'sm'}
                    />
                    <ProFormDigit name={'price'} label="买入价格" rules={[{ required: true }]} />
                    <ProFormDigit name={'volume'} label="买入股数" rules={[{ required: true }]} />
                  </Flex>
                </ProFormList>
              </ProForm>
            ),
            onOk: async () => {
              return batchBuyForm?.validateFields().then(() => {
                const value = batchBuyForm?.getFieldsValue();

                requestBatchBuy(value?.records);
              });
            },
          });
        }}
      >
        批量买入
      </Button>
      <div className="flex">
        <div className="flex-1">
          <ProList<any>
            rowClassName="my-4"
            loading={loading}
            metas={{
              title: {},
              subTitle: {},
              description: {},
              actions: {},
            }}
            dataSource={dataSource}
          />
        </div>
        {/* <div className="flex-1 ml-4"></div> */}
      </div>
    </ProCard>
  );
};

export default Trade;
